/**
  ******************************************************************************
  * @file           : XYXKC_OTA.cpp
  * @author         : admin
  * @brief          : None
  * @attention      : None
  * @date           : 2024/8/20
  ******************************************************************************
  */
#include "XYXKC_OTA.h"
XYXKC_OTA::XYXKC_OTA(void) {

}
XYXKC_OTA::~XYXKC_OTA(void) {

}
int XYXKC_OTA::http_sendRequest(HTTPClient &http) {


    http.useHTTP10(true);
    http.setTimeout(8000);
    http.addHeader("Cache-Control", "no-cache");
    http.addHeader("x-ESP32-version", getVersion());


    int code = http.GET();
    int len = http.getSize();

    if (code == HTTP_CODE_OK) {
        return (len > 0 ? len : 0);
    } else if (code < 0) {
        _error = "Error: " + String(http.errorToString(code).c_str());

        return code;
    } else {
        _error = "Error: HTTP Server response code "+ String(code);

        return -code;
    }
}

bool XYXKC_OTA::http_downloadUpdate(HTTPClient &http, uint32_t size = 0) {
    size = (size == 0 ? http.getSize() : size);
    if (size == 0) {
        return false;
    }
    WiFiClient *client = http.getStreamPtr();

    if (!Update.begin(size, U_FLASH)) {
        _error = "Update.begin failed! " +String(Update.getError());

        return false;
    }

    if (Update.writeStream(*client) != size) {
        _error = "Update.begin failed! " +String(Update.getError());

        return false;
    }

    if (!Update.end()) {
        _error = "Update.end failed! " +String(Update.getError());

        return false;
    }
    return true;
}

void XYXKC_OTA::onProgress(THandlerFunction_Progress fu) {
    Update.onProgress(fu);
}

bool XYXKC_OTA::update(const String url) {
    HTTPClient http;
    http.begin(url);
    return runDate(http);
}
bool XYXKC_OTA::update(const String url, const String token) {
    HTTPClient http;
    http.begin(url);
    http.addHeader("Authorization",String("Bearer ") + String(token));
    return runDate(http);
}
bool XYXKC_OTA::update(const String url, const String username , const String password ) {
    HTTPClient http;
    http.begin(url);
    http.setAuthorization(username.c_str(), password.c_str());
    return runDate(http);
}

bool XYXKC_OTA::runDate(HTTPClient &http){
    int size = http_sendRequest(http);

    if (size > 0) {
        if (http_downloadUpdate(http)) {
            http.end();
            return true;
        }
    } else {
        _error = "Image File not found";

    }

    http.end();
    return false;
}



void XYXKC_OTA::setVersion(String version){
    _x_ESP32_version = version;
}

String XYXKC_OTA::getVersion(){
    return _x_ESP32_version;
}
void  XYXKC_OTA::restart() {
    ESP.restart();
}

String XYXKC_OTA::getError(){
    return _error;
}